const app = getApp()
const utils = require('../../../../common/util/util')
const text = require('../../../../common/util/text')
Page({
  data: {
    xPageReady: true,
    xUserState: false,
    xBuyState: '',
    xProduct: '',
    xNotice: true,
    xReadNoticeState: false,
    xId: '',
    phone: false,
    xContainer:false,
    current:99,
    price:'',
    sku_id:'',
    choose:false,
    active:0,
    product_article_list:[],
    list:[],
    evaluateH:'',
    detailsH:'',
    isnavTop:false,
    is_cell:false,
    channel_id:'',
    doctor_id:'',
    userInfo:{},
    model_show:false,
    time:'',
    period:'', //营期信息
    needSetting:app.globalData.needAuthorization
  },
  onShareAppMessage: function () {
    return {
      title: this.data.xProduct.name,
      path: '/subsale/pages/product/index/index?id=' + this.data.xId,
      imageUrl: 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/share_product_d.jpg?time='+new Date(),
    };
  },
  onLoad: function (options) {
    let that=this;
    that.setData({
      xId: options.id?options.id:'26da8e4962b93a6000ec7c3d68d9d3eb',
      channel_id:options.channel_id?options.channel_id:'',
      doctor_id:options.doctor_id?options.doctor_id:''
    })
    // 绑定渠道
    if(options.channel_id){
      that.user_channel()
    }
    // 产品详情
    that.xInit(that.data.xId)
    // 获取营期信息
    that.xGetPeriod()
  },
  // 获取营期信息
  xGetPeriod:function(){
      let that =this
      wx.cloud.callFunction({
        name: 'product',
        data: {
          action: "get_period_list",
          is_non_channel:true
        }
      }).then(res => {
        that.setData({
          time:res.result.camping_period_begin_date?String(res.result.camping_period_begin_date):'',
          period:res.result,
          dateP:res.result.camping_period_begin_date?utils.formatDate_chinese_monthdate(new Date(res.result.camping_period_begin_date)):''
        })
      })
  },
  xChildReload: function () {
    var pages = getCurrentPages();
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];
      beforePage.xInfo();
    }
  },
  onShow: function () {
    // 用户信息
    this.xGetUser()
  },
  xGetUser:function(){
    let that =this;
    wx.cloud.callFunction({
        name: "user",
        data: {
            action: "detail"
        }
    }).then(res => {
        let user = res.result
        that.setData({
          userInfo:res.result
        })
        if (user.phone_number != undefined && user.phone_number!='') {
          that.setData({
            phone: true  // 已存在手机号
          })
        }else{
          that.setData({
            needSetting:app.globalData.needAuthorization
          })
        }
    })
  },
  // 联系客服
  xMessage:function(){
    var url= 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/cell.png?time='+Date.now() //地址加上时间戳，否则从缓存中加载
    wx.previewImage({
      urls: [url],
    })
  },
  xToqr:function(){
      if(this.data.userInfo.questionnaire_evaluation.length>0){
        wx.navigateTo({
          url: '/subdter/pages/qr/index',
        })
      }
  },
  xSetNav:function(e){
    let that= this;
    let index = e.currentTarget.dataset.index
    if(index==0){
      that.setData({
        active:0
      })
      wx.pageScrollTo({
        duration: 0,
        scrollTop:0
      })
    }else{
      that.setData({
        active:1
      })
      wx.pageScrollTo({
        duration: 0,
        scrollTop:that.data.detailsH+48
      })
    }
  },
  xTodetailA:function(e){
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
        url: '/subtool/pages/article/detail/index?id=' + id,
    })
  },
  xToDetail:function(e){
    let openid = e.currentTarget.dataset.openid
    let totalcomment = e.currentTarget.dataset.totalcomment
    let id= e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/subtool/pages/community/detail/index?id=' + id + '&openid=' + openid +'&totalcomment='+ totalcomment,
    })
  },
  // 患者故事
  xGetStory:function(){
    wx.cloud.callFunction({
      name: 'article',
      data: {
        action: "get_product_article_list"
      }
    }).then(res => {
      this.setData({
        product_article_list:res.result
      })
    })
  },
  xgetS:function(){
    let that =this;
    let list=[]
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
          action: "get_recommended_content_list",
           page_number: 1 //页码
      }
    }).then(res => {
      let data = res.result
      for (var i in data) {
        data[i].release_time = utils.formatTime_emotion(new Date(data[i].release_time))
        list.push(data[i])
      }
      that.setData({
        list:res.result
      })
      var obj =wx.createSelectorQuery()
      obj.selectViewport('.evaluate').scrollOffset(function(res){
        that.setData({
          evaluateH :res.scrollHeight
        })
      }).exec()
    })
    
  },
  xTochoose :function(){
    // if(this.data.xBuyState.buy_status==1 && this.data.xBuyState.count_down_day==0 ){
    //   this.data.xProduct.sku.splice(0,1)
    //   this.setData({
    //     ['xProduct.sku']:this.data.xProduct.sku
    //   })
    // }
    this.setData({
      xContainer:true
    })
  },
  xToselect :function(e){
    let index = e.currentTarget.dataset.index;
    this.setData({
      current:index,
      price:this.data.xProduct.sku[index].price,
      sku_id:this.data.xProduct.sku[index]._id
    })
  },
  xInit: async function (id) {
    let that = this
    await wx.cloud.callFunction({
				name: "product",
				data: {
					action: "product_detail",
					product_id: id
				},
    }).then(res => {
        let product = res.result
        product.detailHTML= text.text(res.result.detailHTML)
        product.additional.is_buy = false
        that.setData({
          xBuyState: product.additional,
          xProduct: res.result
        })
        // setTimeout(function(){
        //   var obj =wx.createSelectorQuery()
        //   obj.selectAll('.details').boundingClientRect(function(res){
        //     that.setData({
        //       detailsH :res[0].height
        //     })
        //   }).exec()
        // },1000)
        // 用户评价
        // that.xgetS()

    }).catch(err=>{
      wx.showToast({
        title: '加载失败，请稍后重试',
        icon:'none'
      })
    })
    that.setData({
      xPageReady: false,
      is_cell:true
    })
  },
  xToIndex: function (e) {
    let id = e.currentTarget.dataset.id
    let label = e.currentTarget.dataset.label
    let mylike = e.currentTarget.dataset.mylike
    wx.navigateTo({
        url: '/subtool/pages/community/about/index?id=' + id + '&label=' + label + '&mylike=' + mylike,
    })
  },
  xNoticeSelect: function () {
    let that = this
    let notice = that.data.xNotice
    that.setData({
      xNotice: !notice
    })
  },
  xReadNotice: function () {
    let that = this
    let readnotice = that.data.xReadNoticeState
  },
  xToMineTask: function () {
    wx.reLaunch({
      url: '/pages/navigation/using/index',
    })
  },
  xToMineDetail: function () {
    wx.navigateTo({
      url: '/subuser/pages/information/index',
    })
  },
  xToEvaluate:function(){
    wx.navigateTo({
      url: '/subuser/pages/improveData/index?type=product',
    })
  },
  // 绑定渠道
  user_channel:function(){
    let that =this;
    wx.cloud.callFunction({
      name: "user",
      data: {
        action: "login",
        userInfo: {
          channel_id:that.data.channel_id,//渠道id
          doctor_id:that.data.doctor_id //医生id
        },
      },
      success: function (res) {
        app.globalData.user = res.result;
        app.globalData.xCustomer = res.result;
      }
    })
  },
  handleTouchInput:function(){
    this.setData({
      innerShow:true
    })
  },
  changePrivacySetting:function(e){
    this.setData({
      needSetting:false
    })
  },
  // 手机号授权
  xPhone: async function (e) {
    let that = this;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showModal({
        title: '警告',
        content: '如不提供有效手机号我们将无法向您提供有效服务。',
        cancelColor: 'cancelColor',
        showCancel:false
      })
      return false
    } else {
      await wx.cloud.callFunction({
        name: 'user',
        data: {
          action: 'getPhone',
          cloudID: e.detail.cloudID
        },
        success: function (res) {
          wx.cloud.callFunction({
            name: "user",
            data: {
              action: "edit",
              formdata: {
                phone_number: res.result.phoneNumber
              }
            }
          }).then(res => {
            wx.showLoading({
              title: '支付准备中',
            })
            that.paymentNext()
          })
        }
      })
    }
  
  },

  paymentNext: async function () {
    let that = this
    wx.showLoading({
        title: '请稍等',
    })
    let timestamp = "" + (new Date()).getTime()
    await that.prepay(timestamp)
  },
  prepay: function (time) {
    let that = this
    let product = that.data.xProduct
    let obj={
      action: 'prepay',
      camping_period_begin_date:that.data.time,
      productName: product.name,
      price: that.data.xProduct.price,
      timestamp: time,
      productId: product._id,
      planId: product.plan_id,
      sku_id:that.data.sku_id,
    }
    // wx.showModal({
    //   title: '提示',
    //   content: JSON.stringify(obj),
    // })
    wx.cloud.callFunction({
      name: 'payment',
      data: obj,
      success(res) {
        let data = res.result.payment
        that.pay(data)
      }
    })
  },
  
  pay: function (payback) {
    let that = this
    let userstate = that.data.xUserState
    wx.requestPayment({
      timeStamp: payback.timeStamp,
      nonceStr: payback.nonceStr,
      package: payback.package,
      signType: 'MD5',
      paySign: payback.paySign,
      success(res) {
        wx.hideLoading({
          success: (res) => {
            if(that.data.xId !=='617ef50c622575a00a1ea51026fc3837'){
              wx.reLaunch({
                url: '/pages/navigation/using/index',
              })
            }else{
              if(that.data.userInfo.questionnaire_evaluation.length>0){
                wx.redirectTo({
                  url: '/subdter/pages/qr/index',
                })
              }else{
                wx.showModal({
                  title: '支付成功',
                  content: '访谈前，需要您花费5~8分钟填写一份评估问卷，以便咨询师了解您的基本状况。',
                  showCancel: true,
                  cancelText: "晚点再说",
                  confirmText: "现在开始",
                  cancelColor: "#9a9a9a",
                  confirmColor: "#BC91F2",
                  success: res => {
                    if (res.confirm) {
                      wx.redirectTo({
                        url: '/subuser/pages/improveData/index?type=product&path=index',
                      })
                    } 
                  }
                })
              }
            }
          },
        })
      },
      fail(res) {
        console.log("支付失败", res)
        wx.hideLoading()
      },
      complete(res) {
        console.log("支付完成,complete res :", res)
        wx.hideLoading()
      }
    })
  },
  modelHidden:function(){
    wx.reportEvent("event_cancel_analysis", {
      "key":false
    })
    this.setData({
      model_show:false
    })
  },
  // 试听
  Audition:function(){
      let that =this;
      that.setData({
        model_show:false
      })
      wx.cloud.callFunction({
        name: 'digital_therapy_extend',
        data: {
            action: "enable_audition"
        }
      }).then(res => {
        wx.reLaunch({
          url: '/pages/navigation/using/index',
        })
      })
  },
  xToResearch:function(){
    wx.reportEvent("event_go_analysis", {
      "key":true
    })
    // wx.redirectTo({
    //   url: '/subuser/pages/research/index?type=2&enable_audition=true&title=疼痛影响因素综合分析&product_id='+this.data.xId,
    // })
    wx.redirectTo({
      url: '/subuser/pages/improveData/index',
    })
  },
  Audition_before:function(){
    let that =this;
    if(!that.data.phone){
      let path = '/subsale/pages/product/index/index?id='+ that.data.xId 
      wx.redirectTo({
        url: '/pages/navigation/login/index?path='+ path ,
      })
    }else{
      if(that.data.xProduct.is_situation_analysis){
        if(that.data.userInfo.questionnaire_evaluation.length>0){
          that.Audition()
        }else{
          that.setData({
            model_show:true
          })
        }
      }else{
        that.Audition()
      }
    }
    
  }
})